package com.robaone.gwt.jsonp.client;


public class JSONPHandler {
	/**
	 * Make call to remote server.
	 */
	@SuppressWarnings("unchecked")
	public static void getJson(String requestId, String url,JsonHandler handler){
		JSONPHandler.getJson(requestId, url, handler,2000);
	}
	/**
	 * Make call to remote server.
	 */
	@SuppressWarnings("unchecked")
	public native static void getJson(String requestId, String url,
			JsonHandler handler,int timeout) /*-{
	   var callback = "callback" + requestId;

	   // [1] Create a script element.
	   var script = document.createElement("script");
	   script.setAttribute("src", url+requestId);
	   script.setAttribute("type", "text/javascript");

	   // [2] Define the callback function on the window object.
	   window[callback] = function(jsonObj) {
	   // [3]
	     handler.@com.robaone.gwt.jsonp.client.JsonHandler::handleJsonResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(jsonObj);
	     window[callback + "done"] = true;
	   }

	   // [4] JSON download has 1-second timeout.
	   setTimeout(function() {
	     if (!window[callback + "done"]) {
	       handler.@com.robaone.gwt.jsonp.client.JsonHandler::handleJsonResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(null);
	     }

	     // [5] Cleanup. Remove script and callback elements.
	     document.body.removeChild(script);
	     delete window[callback];
	     delete window[callback + "done"];
	   }, timeout);

	   // [6] Attach the script element to the document body.
	   document.body.appendChild(script);
	  }-*/;
}
